<template>
  <div class="batchBox">
    <div class="return" @click="back">
      <img class="backImg" src="@/assets/images/back.png" alt />
    </div>

    <el-form
      ref="detail"
      label-position="right"
      label-width="130px"
      :rules="rules"
      :model="detail"
      size="mini"
      class="formBox"
    >
      <el-form-item label="销售部门:" prop="shop_id">
        <el-input v-model="detail.shop_name" class="w200" readonly></el-input>
      </el-form-item>
      <el-form-item label="客户姓名:" prop="uid">
        <el-input v-model="detail.consignee" class="w200" readonly></el-input>
      </el-form-item>
      <el-form-item size="mini" label="开单人 " prop="sale_id">
        <el-select
          v-model="detail.sale_id"
          class="w200"
          filterable
          clearable
          @change="changeSale"
        >
          <el-option
            v-for="item in options.staff"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退货日期:" prop="deal_time">
        <el-date-picker
          v-model="detail.deal_time"
          type="date"
          class="w200"
          value-format="yyyy-MM-dd"
          placeholder="请选择业务日期"
        />
      </el-form-item>

	  <!-- <el-form-item label="业务类型:" prop="business_type">
	    <el-select
	      v-model="detail.business_type"
	      class="w200"
	      clearable
	      placeholder="请选择业务类型"
	      @change = "business_type"
	    >
	      <el-option
	        v-for="item in options.business_type"
	        :key="item.id"
	        :label="item.name"
	        :value="item.id"
	      />
	    </el-select>
	  </el-form-item> -->

	  <!-- <el-form-item size="mini" label="项目明细" prop="business_two_type" v-if="isShowBusinessTwoType">
	      <el-select
	        v-model="detail.business_two_type"
	        placeholder="请选择"
	        class="w200"
	      >
	        <el-option
	          v-for="item in options.business_two_type"
	          :key="item.id"
	          :label="item.name"
	          :value="item.id"
	        />
	      </el-select>
	  </el-form-item> -->



	  <!-- <el-form-item label="项目类型:" prop="project_type">
	    <el-select
	      v-model="detail.project_type"
	      class="w200"
	      clearable
	      placeholder="请选择项目类型"
	    >
	      <el-option
	        v-for="item in options.project_type"
	        :key="item.id"
	        :label="item.name"
	        :value="item.id"
	      />
	    </el-select>
	  </el-form-item> -->

	  <el-form-item label="订单类型:" prop="order_type">
	    <el-select
	      v-model="detail.order_type"
	      class="w200"
	      clearable
	      placeholder="请选择订单类型"
	    >
	      <el-option
	        v-for="item in options.order_type"
	        :key="item.id"
	        :label="item.name"
	        :value="item.id"
	      />
	    </el-select>
	  </el-form-item>

      <!-- <el-form-item label="退货本金" prop="pay_amount">
        <el-input v-model="detail.pay_amount" class="w200" clearable>
          <span slot="append">元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="退货赠金" prop="gift_amount">
        <el-input v-model="detail.gift_amount" class="w200" clearable>
          <span slot="append">元</span>
        </el-input>
      </el-form-item>

      <el-form-item label="退货店转" prop="shop_transfer_amount">
        <el-input v-model="detail.shop_transfer_amount" class="w200" clearable>
          <span slot="append">元</span>
        </el-input>
      </el-form-item> -->

      <el-form-item label="销售组织" >
        <el-select
          v-model="detail.sales_organization"
          @change="changeSales"
          placeholder="请选择"
          class="w200"
        >
          <el-option
            v-for="item in options.market"
            :key="item.marketKingdeeCode"
            :label="item.marketName"
            :value="item.marketKingdeeCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库存组织" >
        <el-select
          v-model="detail.settlement_organization"
          @change="changeSettlement"
          placeholder="请选择"
          class="w200"
        >
          <el-option
            v-for="item in options.market"
            :key="item.marketKingdeeCode"
            :label="item.marketName"
            :value="item.marketKingdeeCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item size="mini" label="库存部门:">
            <el-input v-model="detail.delivery_name" class="w200" readonly />
          </el-form-item>
      <el-form-item size="mini" label="发货仓库" prop="house_code">
        <el-select
          v-model="detail.house_code"
          class="w200"
          clearable
          @change="changeHouse"
        >
          <el-option
            v-for="item in options.house"
            :key="item.kingdeeCode"
            :label="item.name"
            :value="item.kingdeeCode"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="促销政策:">
        <el-select
          v-model="detail.sales_policy"
          filterable
          class="w200"
          clearable
        >
          <el-option
            v-for="item in options.sales_policy"
            :key="item.sales_policy"
            :label="item.sales_policy_name"
            :value="item.sales_policy"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item size="mini" label="是否体验">
        <el-radio v-model="detail.is_experience" label="0">否</el-radio>
        <el-radio v-model="detail.is_experience" label="1">是</el-radio>
      </el-form-item> -->
      <!-- <el-form-item
        v-if="detail.is_experience == 1"
        size="mini"
        label=" 体  验  人 "
        prop="experience_id"
      >
        <el-select
          v-model="detail.experience_id"
          class="w200"
          filterable
          clearable
          @change="changeExperiencc"
        >
          <el-option
            v-for="item in options.staff"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item size="mini" label="是否外联">
        <el-radio v-model="detail.is_outreach" label="0">否</el-radio>
        <el-radio v-model="detail.is_outreach" label="1">是</el-radio>
      </el-form-item> -->
      <!-- <el-form-item
        v-if="detail.is_outreach == 1"
        size="mini"
        label=" 外 联 人 "
        prop="outreahc_id"
      >
        <el-select
          v-model="detail.outreahc_id"
          class="w200"
          filterable
          clearable
          @change="changeOutreahc"
        >
          <el-option
            v-for="item in options.staff"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item size="mini" label="是否转介绍">
        <el-radio v-model="detail.is_introduction" label="0">否</el-radio>
        <el-radio v-model="detail.is_introduction" label="1">是</el-radio>
      </el-form-item> -->
      <!-- <el-form-item
        v-if="detail.is_introduction == 1"
        size="mini"
        label="转介绍人 "
        prop="introduction_id"
      >
        <el-select
          v-model="detail.introduction_id"
          class="w200"
          filterable
          clearable
          @change="changeIntroduction"
        >
          <el-option
            v-for="item in options.staff"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
	  <el-form-item size="mini" label="收入类型" prop="income_type">
	    <el-select
	      v-model="detail.income_type"
	      placeholder="请选择"
	      class="w200"
	    >
	      <el-option
	        v-for="item in options.income_type"
	        :key="item.id"
	        :label="item.name"
	        :value="item.id"
	      />
	    </el-select>
	  </el-form-item>
      <el-form-item label="订单描述:">
        <el-input
          v-model="detail.description"
          class="w200"
          placeholder="请填写订单描述"
          type="textarea"
        />
      </el-form-item>
      <div class="center">
        <el-form-item label="退货单商品:">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            :disabled="detail.goods_type == 0"
            @click="handleProduct('add')"
            >新增</el-button
          >
        </el-form-item>
      </div>
      <div class="center">
        <el-table
          :data="goods"
          size="small"
          class="mb20"
          :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass"
        >
          <el-table-column label="商品名称" width="150"> 
            <template slot-scope="scope">
              <el-select
                v-model="goods[scope.$index].name"
                size="mini"
                value-key="id"
                placeholder="请选择商品"
                filterable
                @focus="selectFocus"
                :remote-method="remoteMethod"
                @change="(val) => selectChange(val, goods[scope.$index],scope.$index)"
              >
                <el-option
                  v-for="(item, index) in product"
                  :key="index"
                  :label="item.zu_name"
                  :value="item"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="商品名称-别名" width="120">
            <template scope="{$index}">
              <el-input v-model="goods[$index].goods_alias_name" placeholder="请输入商品名称-别名" size = 'mini'></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="金蝶编码" prop="kingdee_code" width="160"/> -->
          <el-table-column label="* 业务类型" width="120">
              <template slot-scope="{ row ,$index}" >
                <span >
                  <el-select
                    v-model="row.business_type"
                    size="mini"
                    value-key="id"
                    placeholder="请选择业务类型"
                    :disabled="row.name == '' ? true:false || row.prestock_type == 1"
                    filterable
                    @change="(val) => businessChange(row,$index)"
                  >
                    <el-option
                      v-for="(item, index) in options.business_type"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.disabled"
                    />
                  </el-select>
                </span>
              </template>
          </el-table-column>

          <el-table-column label="* 项目二级分类" width="150">
              <template slot-scope="{ row ,$index}">
                <span>
                  <el-select
                    v-model="row.business_two_type"
                    size="mini"
                    value-key="id"
                    placeholder="项目二级分类"
                   :disabled="row.business_type ==2 ?false:true "
                    filterable
                    @change="(val) => businessChange(row,$index)"
                  >
                    <el-option
                      v-for="(item, index) in options.business_two_type"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </span>
              </template>
          </el-table-column>
          <el-table-column label="标准单价" prop="goods_price" width="120"/>
          <el-table-column label="规格名称" prop="spec_name" width="120"/>
          <el-table-column label="* 是否赠品" >
            <template scope="{row,$index}">
              <span>
                <el-checkbox v-model="goods[$index].checked" :disabled="row.prestock_type  == 1 || row.is_project == 2" @change="(value) => changeGift(value, $index)">是</el-checkbox>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="是否退预存货" width ="120">
                <template slot-scope="{ row ,$index }">
                  <el-select v-model="row.prestock_type"  
                  size="mini" 
                  :disabled="row.is_project == 2 || row.name == '' ? true:false"
                  placeholder="请选择"
                  @change="(value) => businessPrestockTypeChange(goods[$index], $index)">
                    <el-option
                      v-for="(item, index) in options.is_perstock_sales_return"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
          </el-table-column>

          <el-table-column label="卡项列表" width ="120">
                <template slot-scope="{ row ,$index }">
                  <div v-if="row.prestock_type == 2 && row.is_project == 2">
                  <el-button type="text" @click =serviceGoodsDetail(row,$index)>查看</el-button>
                  <!-- 查看1 -->
                </div>
                <div v-else>
                  ----
              </div>
                </template>
          </el-table-column>

          <el-table-column label="* 数量"  width="150">
            <template scope="{row,$index}">
              <div v-if="row.prestock_type == '1'">
                  {{row.number}}
                  <el-button type="text" @click =perstockGoodsDetail(row,$index)>查看</el-button>
              </div>
              <div v-else>
                <el-input-number
                  v-if="row.kingdee_code != '101.12.098'"
                  v-model="row.number "
                  :min="row.is_project == 2 ? 0 : 0.01"
                  :precision="2"
                  :disabled="row.is_project == 2 ? true:false"
                  size="mini"
                />
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="* 退款单价"  width="150">
            <template scope="{row,$index}">
              <div v-if="row.prestock_type != '1'">
                  <el-input-number
                  v-if="goods[$index].is_gift == 0"
                  v-model="goods[$index].pay_price"
                  :min="0.0"
                  :precision="2"
                  size="mini"
                  @change="(value) => priceChange(value, $index)"
                />
                <el-input-number
                  v-else
                  v-model="goods[$index].pay_price"
                  :min="0.0"
                  :precision="2"
                  size="mini"
                  disabled
                  @change="(value) => priceChange(value, $index)"
                />
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="退货款总额" width="150">
            <template  scope="{row,$index}">
              {{row.sales_total}} 
             
            </template>
          </el-table-column>
          <el-table-column label="* 退货本金"  width="150">
            <template scope="{row,$index}">
              <div>
                <!-- || (row.prestock_type == 2 && row.is_project == 2) -->
                  <el-input-number
                  :disabled="row.prestock_type == 1 || (row.prestock_type == 2 && row.is_project == 2)"
                  v-model="goods[$index].refund_principal_price"
                  :min="0.0"
                  :precision="2"
                  size="mini"
                  @change="(value) => priceChange(value, $index,'bj')"
                />
              </div>
    
            </template>
          </el-table-column>
          <el-table-column label="* 退货赠金" width="150">
            <template scope="{row,$index}">
              <div>
                <!-- || (row.prestock_type == 2 && row.is_project == 2) -->
                  <el-input-number
                  v-model="goods[$index].gift_price"
                  :min="0.0"
                  :precision="2"
                  size="mini"
                  :disabled="row.prestock_type == 1 || (row.prestock_type == 2 && row.is_project == 2)"
                  @change="(value) => priceChange(value, $index,'zj')"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="* 退货店转" width="150">
            <template scope="{row,$index}">
          
              <div>
                <!-- || (row.prestock_type == 2 && row.is_project == 2) -->
                  <el-input-number
                  v-model="goods[$index].shop_transfer_price"
                  :min="0.0"
                  :precision="2"
                  size="mini"
                  :disabled="row.prestock_type == 1 || (row.prestock_type == 2 && row.is_project == 2)"
                  @change="(value) => priceChange(value, $index,'dz')"
                />
              </div>
             
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="{ row }">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle
                @click="clickDel(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="center" style="text-align: right">
        <span>应退金额：{{ this.detail.total_amount }}元</span>
        <span class="ml20">实退金额：{{ this.detail.total_amount }}元</span>
      </div>
      <div class="btnBox">
        <el-button
          type="primary"
          size="mini"
          class="mainBtn"
          @click="submitForm('detail')"
          >完成，提交</el-button
        >
      </div>
    </el-form>
    <el-dialog
      title="预存货列表"
      :visible.sync="prestockPopup"
      :close-on-click-modal="false"
      width="1000px"
      @close="closePrestockTicket"
    >
      <div>
        <el-row type="flex" justify="space-between" class="mt20">
          <el-col :span="24">
            <el-table
              :data="prestockList"
              size="small"
              border
              :cell-style="$style.cellStyle"
              :header-cell-style="$style.rowClass"
            >
              <ElTableColumn label="商品名称" prop="goods_name" fixed width="160" />
              <el-table-column label="商品类型" prop="is_project" >
                <template slot-scope="{ row }">
                  <span v-if="row.is_project == 1">商品</span>
                  <span v-if="row.is_project == 2">项目</span>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="spec_name" />
              <el-table-column label="标准价格" prop="goods_price" />
              <el-table-column label="销售单价" prop = "pay_price"  />
              <el-table-column label="预存时间" prop = "prestock_time"  />
              <el-table-column label="剩余预存量" prop="max_num" />
              <el-table-column label="* 出货数量" width="160">
                <template scope="{row}">
                  <el-input-number
                    v-model="row.shipment_num"
                    :precision="2"
                    :min = "0"
                    :step="0.01"
                    size="mini"
                    @change="(value) => handleChange(value , '' ,'prestock')"
                  />
                </template>
              </el-table-column>
            </el-table>
            <div class="flexSb mt20">
              <div></div>
              <div class="mr20 mb20">
                数量合计:
                <span class="peril">{{ sum_total }}个</span>
              </div>
              <div class="mr20 mb20">
                退款总额:
                <span class="peril">{{ refund_total }}元</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="prostockShipmentVerify()">确定</el-button>
      </span>
    </el-dialog>
    
    <el-dialog
      title="卡项列表"
      :visible.sync="servicePopup"
      :close-on-click-modal="false"
      width="1200px"
      @close="closeServiceTicket"
    >
      <div>
        <el-row type="flex" justify="space-between" class="mt20">
          <el-col :span="24">
            <el-table
              :data="serviceList"
              row-key="id"
              size="small"
              border
              @selection-change="handleSelectionChange"
              :cell-style="$style.cellStyle"
              :header-cell-style="$style.rowClass"
            >
            <el-table-column
              type="selection"
              width="55"
              >
            </el-table-column>
            <!-- <ElTableColumn label="选项" prop="goods_name" fixed width="160" >
              <template slot-scope="{ row }">
                  <el-checkbox v-model="row.checked"></el-checkbox>
                </template>
            </ElTableColumn> -->
              <el-table-column label="商品名称" prop="name" />
              <el-table-column label="卡类型" prop="service_type_text" />
              <el-table-column label="日期或次数" prop="numortime" />
              <el-table-column label="*退货次数" width="160">
                <template scope="{row}">
                  <el-input-number
                    v-model="row.refund_num"
                    :precision="2"
                    :min = "0"
                    :max = "parseInt(row.surplus_num)"
                    :step = "1"
                    size="mini"
                    @change="(value) => handleChange(value , '' ,'prestock')"
                    v-if="row.service_type == 2"
                  />
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column label="*退货本金" width="160">
                <template scope="{row}">
                  <el-input-number
                    v-model="row.refund_bj"
                    :precision="2"
                    :min = "0"
                    :max = "parseFloat(row.surplus_bj)"
                    :step="0.01"
                    size="mini"
                  />
                </template>
              </el-table-column>
              <el-table-column label="*退货赠金" width="160">
                <template scope="{row}">
                  <el-input-number
                    v-model="row.refund_zj"
                    :precision="2"
                    :min = "0"
                    :max = "parseFloat(row.surplus_zj)"
                    :step="0.01"
                    size="mini"
                  />
                </template>
              </el-table-column>
               <el-table-column label="*退货店转" width="160">
                <template scope="{row}">
                  <el-input-number
                    v-model="row.refund_dz"
                    :precision="2"
                    :min = "0"
                    :max = "parseFloat(row.surplus_dz)"
                    :step="0.01"
                    size="mini"
                  />
                </template>
              </el-table-column>
            
            </el-table>
            <div class="flexSb mt20">
              <div></div>
            </div>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="repayCardConfirm()">确定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
import { staffListS } from "@/api/staff";
import { shopDetail, shopMarket,shopStore } from "@/api/shop";
import { goodsList } from "@/api/goods";
import { goodsDetailList,prostockShipmentVerify } from '@/api/prestock'
import {
  refundMode,
  createRefundGoods,
  saleList,
  houseList,
  getCustomerService
} from "@/api/order";
class Detail {
  type = 2;
  shop_id = "";
  shop_name = "";
  uid = "";
  consignee = "";
  market_id = "";
  market_name = "";
  sale_id = ""; //开单人id
  sale_name = ""; //开单人名称
  sales_organization = ""; // 销售组织编码
  sales_name = ""; // 销售组织名称
  settlement_organization = ""; // 库存组织编码
  settlement_name = ""; // 库存组织名称
   delivery_name = ''; // 发货部门
  delivery_king = ''; // 发货部门编码
  house_code = ""; // 发货仓库
  house_code_name = "";
  is_experience = "0"; // 是否体验
  experience_id = ""; // 体验人id
  experience_name = ""; // 体验人姓名
  is_outreach = "0"; // 是否外联
  outreahc_id = ""; // 外联人id
  outreahc_name = ""; // 外联人姓名
  is_introduction = "0"; // 是否转介绍
  introduction_id = ""; // 转介绍id
  introduction_name = ""; // 转介绍姓名
  deal_time = ""; //	业务日期
  business_type = ""; //业务类型
  business_two_type = ""; //业务类型
  order_type = ""; //订单类型
  project_type = "";//项目类型
  income_type = ''; // 收入类型
  sales_policy = ""; //	促销政策
  description = ""; //	订单描述

  pay_amount = ""; //销售金额
  gift_amount = ""; //	预存赠送金额
  total_amount = 0; //合计金额

  goodsList = [];
}
class Rules {
  sale_id = [{ required: true, message: "请选择开单人", trigger: "change" }];
  sales_organization = [
    { required: true, message: "请选择销售组织", trigger: "change" },
  ];
  settlement_organization = [
    { required: true, message: "请选择库存组织", trigger: "change" },
  ];
  house_code = [
    { required: true, message: "请选择发货仓库", trigger: "change" },
  ];
  business_type = [
    { required: true, message: "请选择业务类型", trigger: "change" },
  ];
  order_type = [
    { required: true, message: "请选择订单类型", trigger: "change" },
  ];

  refund_type = [
    { required: true, message: "请选择收款类型", trigger: "change" },
  ];

  income_type = [
    { required: true, message: '请选择收入类型', trigger: 'change' }
  ];
  deal_time = [
    { required: true, message: "请选择业务日期", trigger: "change" },
  ];
  pay_amount = [
    { required: true, message: "请输入销售金额", trigger: "change" },
    {
      pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
      message: "最多保留两位小数",
      trigger: "change",
    },
  ];
  gift_amount = [
    { required: true, message: "请输入预存赠送金额", trigger: "change" },
    {
      pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
      message: "最多保留两位小数",
      trigger: "change",
    },
  ];
  shop_transfer_amount = [
    { required: true, message: "请输入店转金额", trigger: "change" },
    {
      pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
      message: "最多保留两位小数",
      trigger: "change",
    },
  ];
  experience_id = [
    { required: true, message: "请选择体验人", trigger: "change" },
  ];
  outreahc_id = [
    { required: true, message: "请选择外联人", trigger: "change" },
  ];
  introduction_id = [
    { required: true, message: "请选择转介绍人", trigger: "change" },
  ];
}
class Options {
  constructor() {
    this.uid = [];
    this.shop_id = [];
    this.market = [];
    this.business_type = [
      { id: 1, name: "疤痕" },
      { id: 2, name: "项目" },
      { id: 3, name: "青春痘" },
      { id: 4, name: "护肤品" }
    ];
    this.order_type = [
      { id: 1, name: "新单" },
      { id: 2, name: "补单" },
    ];
 
	this.income_type = [
	  { id: 1, name: '服务（各类疗程卡项及疗程卡项赠送产品）' },
	  { id: 2, name: '产品销售（单独付费购买产品）' },
	  { id: 3, name: '医美收入' },
	];

  this.project_type = [
	  { id: 1, name: '手术' },
	  { id: 2, name: '注射' },
	  { id: 3, name: '光电' },
    { id: 4, name: '生美皮肤' },
    { id: 5, name: '身体' },
	];
  this.business_two_type = [
      { id: 1, name: "身体项目" },
      { id: 2, name: "皮肤项目" },
  ];

    this.refundMode = [];
    this.staff = [];
    this.house = [];
    this.sales_policy = [];
  };
  is_perstock_sales_return  =[
    {id:1, name:'是'},
    {id:2, name:'否'},
  ];
}
class Goods {
  id = "";
  prestock_type = "";
  name = "";
  kingdee_code = "";
  goods_price = "";
  spec_name = "";
  number = 1;
  unit_code = "";
  is_gift = "";
  checked = false;
  pay_price = "";
  house_code = "";
  house_code_name = "";
  goods_deal_time = "";
  business_two_type = ""; //业务类型
  business_type = "";
  service = [];//卡项列表
  prestock =  []; //预存货列表
  descs = "";
  out_num = 0; //出/存货数量
  sales_total = 0; //退货款总额总额-单商品
  refund_principal_price = 0; //退货本金
  gift_price = 0; //退货赠金
  shop_transfer_price = 0; //退货店转
}
export default {
  data() {
    return {
      detail: new Detail(),
      rules: new Rules(),
      goods: [new Goods()], // 已选列表
      options: new Options(), // 选项
      loading: false,
      product: [],
      prestockPopup: false,// 预存货列表弹窗
      servicePopup: false,// 卡项列表弹窗
      serviceList:[],   //卡项列表
      prestockList: [], // 预存货商品列表
      sum_total:0,      //预存货退货数量
      refund_total:0,//预存货退款总额
      now_index:0    // 当前商品下标
    };
  },
  mounted() {
    this.detail.shop_id = this.$route.query.detail.shop_id;
    this.detail.shop_name = this.$route.query.detail.shop_name;
    this.detail.uid = this.$route.query.detail.id;
    this.detail.customer_id = this.$route.query.detail.id;
    this.detail.consignee = this.$route.query.detail.customer_name;
    this.getOptions();
  },
  methods: {
    businessPrestockTypeChange(e,index){
      this.now_index = index
      this.goods[this.now_index].prestock = [];
      this.prestockList = [];
      // 是预存货
      if(e.prestock_type == 1){
        this.goods[this.now_index].business_type = '';
        this.goods[this.now_index].business_two_type = '';
        this.goods[this.now_index].checked = '';
        this.goods[this.now_index].refund_principal_price = 0;
        this.goods[this.now_index].gift_price = 0;
        this.goods[this.now_index].shop_transfer_price = 0;
        this.goods[this.now_index].sales_total = 0;
        this.goods[this.now_index].number = 0;
      }else{
        // 否预存货
        this.goods[this.now_index].refund_principal_price = 0;
        this.goods[this.now_index].gift_price = 0;
        this.goods[this.now_index].shop_transfer_price = 0;
        this.goods[this.now_index].number = 0;
        this.goods[this.now_index].sales_total = 0;
      }
      this.goodsUniqueVerify(e,index);
      this.getSummaries();      
    },
    truncateDecimal(num) {
      let numStr = num.toString();
      let dotIndex = numStr.indexOf('.');
      if (dotIndex === -1) {
          return num;
      }
      // 截取字符串保留到小数点后两位
      return parseFloat(numStr.slice(0, dotIndex + 3));
    },
    //单个预存货商品查看
    perstockGoodsDetail(e,index){
     
      this.sum_total = 0
      this.refund_total = 0
      this.now_index = index
      goodsDetailList({ good_id: e.id,customer_id:this.detail.uid,shop_id:this.detail.shop_id}).then(res => {
        this.prestockPopup = true;
        this.prestockList = res.data
        
      })

    },
    // 关闭预存货弹窗
    closePrestockTicket (e) {
      this.privilegeTotal = 0
      this.leadData = []
      this.privilegeList = []
    },


    business_type(e){
      if(e==2){
        this.isShowBusinessTwoType = true;
        // this.detail.business_two_type = 2;
      }else{
        this.isShowBusinessTwoType = false;
        // this.detail.business_two_type  = "";
      }
    },
    // 获取选项
    getOptions() {
      // 组织
      shopMarket({ shopId: this.detail.shop_id }).then((res) => {
        this.options.market = res;
        this.detail.sales_organization = this.options.market[0].marketKingdeeCode
        this.detail.sales_name = this.options.market[0].marketName
        this.detail.settlement_organization = this.options.market[0].marketKingdeeCode
        this.detail.settlement_name = this.options.market[0].marketName
      });
      // 促销政策
      saleList().then((res) => {
        this.options.sales_policy = res.data.list;
      });
      // 该门店员工
      staffListS({ page: 1, limit: 100000, shopId: this.detail.shop_id }).then(
        (res) => {
          this.options.staff = res.list;
        }
      );
      //该门店仓库
      shopStore({page: 1, limit: 100000, shopId: this.detail.shop_id }).then(res => {
        this.options.house = res.list;
      })
      // 该门店详情
      shopDetail({ shopId: this.detail.shop_id }).then((res) => {
        this.detail.bank_number = res.bankCard;
        this.detail.market_id = res.marketId;
        this.detail.market_name = res.marketName;
        this.detail.delivery_name = res.shopName
        this.detail.delivery_king = res.keycode
      });
      this.getGoods()
    },
        //单个卡项商品查看
    serviceGoodsDetail(e,index){
      this.now_index = index
      console.log(this.goods[this.now_index].service,"11111" )
      if(this.goods[this.now_index].service.length != 0){
            this.serviceList.forEach(serviceItem => {
              const exists = this.goods[this.now_index].service.some(goodService => {
                return goodService.id === serviceItem.id;
              })
              if (exists) {
                serviceItem.checked = true;
              }
            })
            this.servicePopup = true;
          }else{
            getCustomerService({ goods_id:e.id,shop_id:this.detail.shop_id,customer_id:this.detail.uid }).then(
                  res => {
                      this.servicePopup = true;
                      this.serviceList = res.data;
                      console.log(  this.serviceList,"  this.serviceList")
                  })
          }
    },
    // 关闭卡项列表弹窗
    closeServiceTicket (e) {
      this.servicePopup = false;
      // handleSelectionChange

    },
    // 退服务卡项确定
    repayCardConfirm(){
      this.servicePopup = false;
      this.goods[this.now_index].sales_total = 0;
      this.goods[this.now_index].refund_principal_price = 0; //剩余本金
      this.goods[this.now_index].gift_price = 0; //剩余赠金
      this.goods[this.now_index].shop_transfer_price = 0; //剩余店转
       this.goods[this.now_index].service.forEach(item => {
          this.goods[this.now_index].sales_total = parseFloat(item.refund_bj) + parseFloat(item.refund_dz) + parseFloat(item.refund_zj) + this.goods[this.now_index].sales_total ;
          this.goods[this.now_index].refund_principal_price = parseFloat(item.refund_bj) + this.goods[this.now_index].refund_principal_price ;
          this.goods[this.now_index].gift_price =  parseFloat(item.refund_zj) + this.goods[this.now_index].gift_price ;
          this.goods[this.now_index].shop_transfer_price = parseFloat(item.refund_dz) + this.goods[this.now_index].shop_transfer_price;
       })
       this.goods[this.now_index].sales_total.toFixed(2);
       this.goods[this.now_index].refund_principal_price.toFixed(2);
       this.goods[this.now_index].gift_price.toFixed(2);
       this.goods[this.now_index].shop_transfer_price.toFixed(2);
       this.getSummaries();
    },
    handleSelectionChange(val) {
      console.log(this.goods[this.now_index].service,"this.goods[this.now_index].service")
    
        val.forEach(item => item.checked = true);
        this.goods[this.now_index].service = val;
        this.goods[this.now_index].number = val.length
        console.log(this.goods[this.now_index].service,"我被调用了" )
 
      

    },
    //单出预存货验证
    prostockShipmentVerify(){
      prostockShipmentVerify({ prestock_goods:this.prestockList }).then(
        res => {
          // sum_total
          this.prestockPopup = false;
          this.goods[this.now_index].number = res.data.num;
          this.goods[this.now_index].sales_total = res.data.sum_price;
          // this.goods[ this.now_index].out_num = res.data.num
          this.goods[ this.now_index].littleCount = res.data.price;
          this.goods[ this.now_index].prestock = this.prestockList; 
          this.getSummaries();
        }
      )


    },
    //商品数据
    getGoods(name){
      goodsList({page: 1, limit: 100000,zu_name:name?name:''}).then((res) => {
        this.product = res.list;
      });
    },
    // 选择转开单人
    changeSale(e) {
      this.options.staff.forEach((item) => {
        if (e == item.id) {
          this.detail.sale_name = item.name;
        }
      });
    },
    // 选择销售组织
    changeSales(e) {
      this.options.market.forEach((item) => {
        if (e == item.marketKingdeeCode) {
          this.detail.sales_name = item.marketName;
        }
      });
    },
    // 选择库存组织
    changeSettlement(e) {
      this.options.market.forEach((item) => {
        if (e == item.marketKingdeeCode) {
          this.detail.settlement_name = item.marketName;
        }
      });
    },
    //
    // 选择仓库
    changeHouse(e) {
      this.options.house.forEach((item) => {
        if (e == item.kingdeeCode) {
          this.detail.house_code_name = item.name;
        }
      });
    },
     // 选择体验人
    changeExperiencc(e) {
      this.options.staff.forEach((item) => {
        if (e == item.id) {
          this.detail.experience_name = item.name;
        }
      });
    },
    // 选择外联人
    changeOutreahc(e) {
      this.options.staff.forEach((item) => {
        if (e == item.id) {
          this.detail.outreahc_name = item.name;
        }
      });
    },
    // 选择转介绍人
    changeIntroduction(e) {
      this.options.staff.forEach((item) => {
        if (e == item.id) {
          this.detail.introduction_name = item.name;
        }
      });
    },

    // 商品选择前
    selectFocus() {
      if (!this.detail.uid) return this.$message.warning("请先选择客户哦！");
    },
    // 搜索商品
    remoteMethod(e){
      this.getGoods(e)
    },
    // 商品操作
    handleProduct(type) {
      switch (type) {
        case "add":
          let tip = 0
          this.goods.forEach(item => {
            if (item.id == '') {
              tip += 1
            }
          })
          if (tip > 0) {
            this.$message({
              message: '请补全列表中为空商品。',
              type: 'warning'
            })
          } else {
            this.goods.push(new Goods())
          }
          break;
      }
    },
    // 是否赠品
    changeGift(value, index) {
      this.goods[index].shop_transfer_price = 0;
      this.goods[index].gift_price = 0;
      this.goods[index].refund_principal_price = 0;

      this.goods[index].pay_price = 0;
      this.goods[index].number = 0;
      this.goods[index].is_gift = this.goods[index].checked?1:0
      this.priceChange(this.goods[index].pay_price, index);
    },
    // 商品修改
    selectChange(val,scope, index) {
    



      const { goods_price, id, kingdee_code, spec_name, unit_code,is_project } = val;
      this.goods[index].kingdee_code = kingdee_code;
      this.goods[index].id = id;
      this.goods[index].goods_price = goods_price;
      this.goods[index].spec_name = spec_name;
      this.goods[index].unit_code = unit_code;
      this.goods[index].is_project = is_project;

      if(this.goods[index].is_project == 2){
        // 否
        this.goods[index].prestock_type = 2;	

      }else{
        // 空
        this.goods[index].prestock_type = '';	

      }
      this.goods[index].is_gift = 0;
 
    
      this.goods[index].number = 0;
      this.goods[index].shop_transfer_price = 0;
      this.goods[index].gift_price = 0;;
      this.goods[index].refund_principal_price = 0;
      this.goods[index].sales_total = 0;
      this.goods[index].prestock = [];
      this.goods[this.now_index].service = [];
      this.prestockList = []
      this.goodsUniqueVerify(scope,index);
      this.getSummaries();      
    
    },
    // 商品数量
    handleChange(value, index,type='') {
      if(type == 'prestock'){
        this.sum_total = 0
        this.refund_total = 0
        this.prestockList.forEach(item => {
          this.sum_total = (
            parseFloat(this.sum_total ? this.sum_total : 0) +
            parseFloat(item.shipment_num ? item.shipment_num : 0)
          ).toFixed(2)

          this.refund_total = (
            parseFloat(this.refund_total ? this.refund_total : 0) +
            parseFloat(item.shipment_num ? item.shipment_num : 0) *  parseFloat(item.pay_price ? item.pay_price : 0)
          ).toFixed(2)
        })
      }else{
        console.log('123213213','退货本金');
        this.goods[index].littleCount = (
          value * this.goods[index].pay_price
        ).toFixed(2);
        this.getSummaries();
      }
     
    },

    // 退货款本金/赠金/店转
    priceChange(value, index,type) {

      // console.log(value,index,'改变')

      this.goods[index].sales_total = (
        this.goods[index].refund_principal_price + this.goods[index].gift_price + this.goods[index].shop_transfer_price
      ).toFixed(2);
      
     
      this.goods[index].littleCount = (
        this.goods[index].refund_principal_price + this.goods[index].gift_price + this.goods[index].shop_transfer_price 
      ).toFixed(2);
    
    
      // this.goods[index].littleCount = (
      //   value * this.goods[index].number
      // ).toFixed(2);
      this.getSummaries();
    },
    // 合计计算
    getSummaries() {
      this.detail.total_amount = 0;
      this.goods.forEach((item) => {
        console.log(item,item.sales_total,item.shop_transfer_price,item.gift_price,item.refund_principal_price,"item")
        this.detail.total_amount = (
          parseFloat(this.detail.total_amount ? this.detail.total_amount : 0) +
          parseFloat(item.sales_total ? item.sales_total : 0) 
        ).toFixed(2);
      });
    },
    // 同步选中商品
    getDetailGoods() {
      let list = [];
      list = this.goods.map((i) => {
        return i.id;
      });
      let obj = {};
      for (let key in list) {
        obj[key] = list[key];
      }
      this.detail.goodsList = Object.keys(obj).map((val) => ({
        id: obj[val],
      }));
    },
    // 删除单商品
    clickDel(row) {
      this.goods = this.goods.filter((item) => item.id !== row.id);
      this.getSummaries();
    },
    // 提交
    submitForm(formName) {
     
      this.detail.goodsList = this.goods.filter((val) => val.id);
    console.log(this.detail.goodsList,"1111")
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.checking();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //卡项验证
    serviceVerify(row,index){
      console.log(this.detail);
      console.log(123123)
      if(row.is_project == 2){
        //卡项
        getCustomerService({ goods_id:row.id,shop_id:this.detail.shop_id,customer_id:this.detail.uid }).then(
        res => {
          console.log(res);
          if(res){
            this.serviceList = res.data

            
          }else{
            this.goods[index] = [];
          }
        }
      )

      }
    

    },
    //商品列表商品唯一验证
    goodsUniqueVerify(row,index){
      if(this.goods.length > 1){
        let code = 0;
        this.goods.forEach((item,index1) => {
            if (item.id == row.id && item.prestock_type == row.prestock_type && item.business_type == row.business_type&& item.business_two_type == row.business_two_type && index1 !== index) {
              this.$message({
                message: '该商品已经选过',
                type: 'error'
              });
              this.goods.pop(index)
              code+=1
            } 
        })
        if(code>0){
          return false;
        }else{
          return true;
        }
      } else {
        return true;
      }
    },
    //分类改变事件
    businessChange(row,index){
      console.log(row)
      if(row.business_type != 2){
        row.business_two_type = '';
      }
      let isRepeat = this.goodsUniqueVerify(this.goods[index],index)
      if(!isRepeat){
        this.getSummaries('goods')
      }
    },
    // 验证
    checking() {
      if (this.detail.goodsList == 0) {
        this.$message({
          message: "请添加退货商品",
          type: "error",
        });
      } else {
        let number = 0;
        let is_gift = 0;
        let pay_price = 0;
        let business__type = 0;
        let business_two__type = 0;
        let prestock_type = 0;
        let  gift_price = 0;
        let shop_transfer_price = 0;
        this.detail.goodsList.forEach((item) => {
          console.log(item.prestock_type);
          if(item.prestock_type ==2){
            if(!item.business_type){
              business__type +=1;
            }
            if(item.business_type == 2 &&  !item.business_two_type){
              business_two__type +=1;
            }
          }
          
          if(!item.prestock_type){
            prestock_type +=1;
          }
          if (!item.number) {
            number += 1;
          }
          if (item.is_gift === "") {
            is_gift += 1;
          }
          if (item.refund_principal_price === "" && item.gift_price  === "" &&  item.shop_transfer_price === '' ) {
            pay_price += 1;
          }
       
          item["house_code"] = this.detail.house_code;
          item["house_code_name"] = this.detail.house_code_name;
          item["goods_deal_time"] = this.detail.deal_time;
          item["descs"] = "退货";
        });
        let totalAll =
          parseFloat(this.detail.pay_amount) +
          parseFloat(this.detail.gift_amount)+
          parseFloat(this.detail.shop_transfer_amount);
          console.log(number,is_gift,pay_price,business__type, business_two__type,prestock_type);
        // return false;
        if (number > 0 || is_gift > 0 || pay_price > 0  || business__type > 0 ||  business_two__type > 0 || prestock_type >0 ) {
          this.$message({
            message: "请完善退货商品列表",
            type: "error",
          });
        } 


        // else if (totalAll != this.detail.total_amount) {
        //   this.$message({
        //     message: "销售金额 + 预存赠送金额 + 店转金额 = 应退金额?",
        //     type: "error",
        //   });
        // } 
        else {
          this.hint("添加");
        }
      }
    },
    // 提示
    hint(text) {
      this.$confirm(`确定${text}此退货订单吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.confirm();
        console.log(this.detail,"1111111")
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 提交
    async confirm() {
      const loading = this.$loading({
        lock: true,
        text: "提交中，请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        const res = await createRefundGoods({ ...this.detail });
        loading.close();
        this.$message({
          type: "success",
          message: res.msg
        });
        this.back();
      } catch (e) {
        loading.close();
      }
    },
    // 返回
    back() {
      const query = {
        detail: this.$route.query.detail,
        id: this.$route.query.detail.id,
        activeName: "fifth",
      };
      this.$router.push({ name: "客户详情", query });
    },
  },
};
</script>

<style lang="scss" scoped>
.return {
  position: fixed;
  right: 20px;
  top: 71px;
  z-index: 999;
  .backImg {
    margin-right: 14px;
    width: 32px;
    height: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}
.formBox {
  display: flex;
  flex-wrap: wrap;
  .el-form-item {
    width: 33%;
  }
}
.el-radio {
  margin-right: 8px;
}
.center {
  width: 100% !important;
}
.btnBox {
  width: 100%;
  text-align: center;
}
</style>
